package com.atguigu.gulimail.product.aspect;

import com.atguigu.gulimail.product.dao.LogDao;
import com.atguigu.gulimail.product.entity.LogEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Fengkai
 * @creat 2022/9/28
 */
@Aspect
@Component
@Slf4j
public class RequestLogAspect {
    private LogDao logDao;

    @Autowired
    public RequestLogAspect(LogDao logDao){
        this.logDao = logDao;
    }

    @Pointcut("@annotation(com.atguigu.gulimail.product.annotation.RequstLogAnnotation)")
    public void requestLog(){};

    @Before("requestLog()")
    public void saveLog(JoinPoint pointcut){
        Signature signature = pointcut.getSignature();
        String declaringTypeName = signature.getDeclaringTypeName();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        LogEntity logEntity = new LogEntity();
        logEntity.setRequestIp(request.getRemoteAddr() +":" + request.getRemotePort());
        logEntity.setRequestUrl(logEntity.getRequestUrl());
        logEntity.setRequestTime(new Date());
        logDao.insert(logEntity);
    }
}
